package gui.newQuiz;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.List;

import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import quiz.Question;

public class QuestionWindowListener implements ListSelectionListener,
		ActionListener {
	QuestionWindow main;
	int lastSelectedIndex = 0;

	public QuestionWindowListener(QuestionWindow main) {
		this.main = main;
	}

	@Override
	public void valueChanged(ListSelectionEvent e) {
		if (e.getValueIsAdjusting() == false) {
			lastSelectedIndex = main.questionTypes.getSelectedIndex();
			System.out.println("Endret lastSelected til: " + lastSelectedIndex);
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		if (e.getSource().equals(main.addSelectedQuestionType)) {
			main.listSelectedQuestions.addElement(main.listForQuestionTypes
					.get(lastSelectedIndex));
		} else if (e.getSource().equals(main.okButton)) {
			try {
				makeListOfQuestionsAndSendThemToFillInfoGUI();
			} catch (InstantiationException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IllegalAccessException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();

			} catch (ClassNotFoundException e1) {
				e1.printStackTrace();
			}

		}
	}

	private void makeListOfQuestionsAndSendThemToFillInfoGUI() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		List lol = Arrays.asList(main.listSelectedQuestions.toArray());
		for (Object obj : lol) {
			String questionString = String.valueOf(obj);
			Class questionClass = Class.forName("questions."
					+ questionString);
			Question question = (Question) questionClass.newInstance();
			
			SetupQuestions setupQuestion = new SetupQuestions(question);
			main.quiz.addQuestion(question);
			main.dispose();
		}
	}
}